package com.rahms.server.utils;

import com.rahms.common.constant.CacheConstant;
import com.rahms.common.constant.JwtClaimsConstant;
import com.rahms.common.properties.JwtProperties;
import com.rahms.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * JWT Token 工具类
 */
@Component
public class JwtTokenUtil {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 生成JWT令牌
     */
    public String generateToken(Long userId, String username, String phone, String realName) {
        String token = JwtUtil.generateToken(
                userId.toString(),
                jwtProperties.getIssuer(),
                jwtProperties.getSecret(),
                jwtProperties.getTtlSeconds()
        );
        
        // 将token和用户信息缓存到Redis
        String cacheKey = CacheConstant.JWT_TOKEN_CACHE_PREFIX + token;
        redisUtil.set(cacheKey, userId, CacheConstant.JWT_TOKEN_EXPIRE, TimeUnit.SECONDS);
        
        return token;
    }

    /**
     * 解析JWT令牌
     */
    public Claims parseToken(String token) {
        return JwtUtil.parseToken(token, jwtProperties.getSecret());
    }

    /**
     * 从令牌中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return Long.valueOf(claims.getSubject());
    }

    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.get(JwtClaimsConstant.USERNAME, String.class);
    }

    /**
     * 从令牌中获取手机号
     */
    public String getPhoneFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.get(JwtClaimsConstant.PHONE, String.class);
    }

    /**
     * 从令牌中获取真实姓名
     */
    public String getNameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.get(JwtClaimsConstant.NAME, String.class);
    }

    /**
     * 验证令牌是否有效
     */
    public boolean validateToken(String token) {
        try {
            // 先检查Redis缓存
            String cacheKey = CacheConstant.JWT_TOKEN_CACHE_PREFIX + token;
            if (!redisUtil.hasKey(cacheKey)) {
                return false;
            }
            
            // 再验证JWT本身
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 使令牌失效
     */
    public boolean invalidateToken(String token) {
        try {
            String cacheKey = CacheConstant.JWT_TOKEN_CACHE_PREFIX + token;
            return redisUtil.delete(cacheKey);
        } catch (Exception e) {
            return false;
        }
    }
}
